package com.qding.park.manager.service.statis.facade.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qding.park.common.core.cache.service.CacheServiceFacade;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.manager.adapter.factory.AdapterParkProxyFactory;
import com.qding.park.manager.cache.ParkCacheInter;
import com.qding.park.manager.cache.UserCacheInter;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.facade.statis.service.ParkStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.TbParkspace;
import com.qding.park.manager.pojo.TreeParkInfo;
import com.qding.park.manager.service.statis.biz.ParkBiz;
import com.qding.park.manager.service.statis.mapper.TbParkingruleStatisMapper;
import com.qding.park.manager.service.statis.mapper.TbParkspaceStatisMapper;
import com.qding.park.manager.service.statis.mapper.TbProjectStatisMapper;

/**
 * @ClassName: ParkStatisFacadeImpl
 * @Description: 有关车场的统计实现
 * @author Comsys-Administrator
 * @date 2016年10月9日 上午11:44:04
 *
 */
@Service("parkStatisFacade")
public class ParkStatisFacadeImpl implements ParkStatisFacade {
	private static final Logger _log = LoggerFactory.getLogger(ParkStatisFacadeImpl.class);
	@Autowired
	private TbParkspaceStatisMapper tbParkspaceMapper;
	
	@Autowired
	private  TbProjectStatisMapper  tbProjectMapper;
	
	@Autowired
    private TbParkingruleStatisMapper tbParkingruleMapper;
	
	@Autowired
	private  ParkBiz   parkBiz;

	/**
	 * @Field @adapterParkProxyFactory : TODO(底层车场适配器代理工厂)
	 */
	@Autowired
	private AdapterParkProxyFactory adapterParkProxyFactory;

	@Autowired
	private CacheServiceFacade cacheServiceFacade;

	@Autowired
	private ParkCacheInter parkCacheInter;

	@Autowired
	private UserCacheInter userCacheInter;

	/*
	 * <p>Title: 车场综览</p> <p>Description: </p>
	 * 
	 * @param jumpPage
	 * 
	 * @param pageLength
	 * 
	 * @return
	 * 
	 * @see
	 * com.qding.park.manager.facade.statis.service.ParkStatisFacade#overview(
	 * int, int)
	 */

	@Override
	public ParkDataResult overview(int jumpPage, int pageLength,PowerInfo power) throws BaseException {

		PageHelper.startPage(jumpPage, pageLength);
		List<TbParkspace> tbParkspaceList = null;
		
		if(power.isAdminIs()){
			//管理员权限
			tbParkspaceList=tbParkspaceMapper.listAll();
		}else if(!ListUtil.isEmpty(power.getParkList())){
			//管理的车场列表不为空
			tbParkspaceList=tbParkspaceMapper.listInParks(power.getParkList());
		}else{
			//管理的车场为空
			return ParkDataResult.createEmpty();
		}
				

		PageInfo page = new PageInfo(tbParkspaceList);

		List dataList = new ArrayList();
		// if(!ListUtil.isEmpty(tbParkspaceList)){
		for (TbParkspace park : tbParkspaceList) {
			Map<String, Object> map = new HashMap<String, Object>();
			Date lastTime = cacheServiceFacade.queryParkonlinetime(String.valueOf(park.getSupplierId()),
					park.getParkCode());
			map.put("cityName", "城市1");
			map.put("propertyName", park.getPropertyName());
			map.put("projectName", park.getName());
			map.put("parkId", park.getId());
			dataList.add(map);
		}
		// }

		ParkDataResult parkDataResult = ParkDataResult.createListDate(dataList, page);
		return parkDataResult;
	}

//	private int getParkspaceNum(AdapterProxy adapterProxy, TbParkspace park) {
//		int tempStopNum = -1;
//		try {
//		    AdParkInfo  parkInfo = adapterProxy.getParkAdapter().getTempStopNum(park.getParkCode());// 查询实时车场临停车位数
//		    tempStopNum=parkInfo.getRestSpace();
//		} catch (Exception e) {
//			_log.error(e, e);
//		}
//		return tempStopNum;
//	}

//	private String getOnlineStatus(AdapterProxy adapterProxy, TbParkspace park) {
//		String temp = "";
//		try {
//			List<ApPark> apParks = adapterProxy.getParkAdapter().queryParkConnStatus(park.getParkCode());
//			temp = (apParks.get(0).getLastRequestTime() == null ? ""
//					: DateUtils.formatDate(apParks.get(0).getLastRequestTime(), DateUtils.DATE_FORMAT_DATETIME)) + " "
//					+ (Integer.valueOf(apParks.get(0).getConnState()) == 1 ? "在线" : "离线");
//			cacheServiceFacade.updateParkonlinetime(String.valueOf(park.getSupplierId()), park.getParkCode());
//		} catch (Exception e) {
//			_log.error(e, e);
//			Date timeout = cacheServiceFacade.queryParkonlinetime(String.valueOf(park.getSupplierId()),
//					park.getParkCode());
//			temp = (timeout == null ? "" : DateUtils.formatDate(timeout, DateUtils.DATE_FORMAT_DATETIME)) + " " + "离线";
//		}
//		return temp;
//	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.qding.park.manager.facade.statis.service.ParkStatisFacade#listall(
	 * java.lang.String, java.lang.String, java.lang.String) 获取车场列表 如果根据用户id,
	 */
	@Override
	public ParkDataResult listall(String tel, String bjuserid, String bjprojectId) throws BaseException {
		String userIdstr = userCacheInter.bjuserId2userId(bjuserid);
		List<TbParkspace> parkList = new ArrayList<TbParkspace>();
		if (StringUtils.isBlank(userIdstr)&&!StringUtils.isBlank(bjprojectId)) {
			// throw new
			// ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getId(),
			// null,
			// ExceptionMessage.createExceptionMessage(
			// ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_INVALID.getDesc(),
			// "没有此用户信息",
			// " phone=" + tel + ",bjuserId=" + bjuserid));
			String[] paramsArray=bjprojectId.split(",");
			parkList = tbParkspaceMapper.listAllByProject(paramsArray);
		}

		if (ListUtil.isEmpty(parkList)&&!StringUtils.isBlank(userIdstr)) {
			int userId = Integer.valueOf(userIdstr);

			parkList = tbParkspaceMapper.queryParksByUserId(userId);

			if (ListUtil.isEmpty(parkList)&&!StringUtils.isBlank(bjprojectId)) {
				String[] paramsArray=bjprojectId.split(",");
				parkList = tbParkspaceMapper.listAllByProject(paramsArray);
			}
		}

		List dataList = new ArrayList();
		for (TbParkspace park : parkList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("parkId", park.getId());
			map.put("parkName", park.getParkName());
			dataList.add(map);
		}
		ParkDataResult parkDataResult = ParkDataResult.createListDate();
		parkDataResult.putDataOnList(dataList);
		return parkDataResult;
	}

//	@Override
//	public ParkDataResult status(int parkId) throws BaseException {
//		TbParkspace park = parkCacheInter.queryParkSpace(parkId);
//		Map<String, Object> map = new HashMap<String, Object>();
//		int supplierId = park.getSupplierId();// 车场软件供应商id
//		// 根据车场id对应接口
//		AdapterProxy adapterProxy = adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
//		// int tempStopNum =
//		// adapterProxy.getParkAdapter().getTempStopNum(park.getParkCode());//
//		// 查询实时车场临停车位数
//		int tempStopNum = getParkspaceNum(adapterProxy, park);
//		List<ApPark> apParks = adapterProxy.getParkAdapter().queryParkConnStatus(park.getParkCode());
//		map.put("remainParkingSpaces", tempStopNum);
//		map.put("onlineStatus", getOnlineStatus(adapterProxy, park));
//		ParkDataResult parkDataResult = ParkDataResult.createObjDate();
//		parkDataResult.putMapOnObj(map);
//		return parkDataResult;
//	}

	@Override
	public ParkDataResult listall(PowerInfo power) throws BaseException {
//		List<TbParkspace> parkList = tbParkspaceMapper.listInParks(power.getParkList());
		List<TbParkspace> parkList ;
		if(power.isAdminIs()){
			parkList = tbParkspaceMapper.listAll();
		}else{
			parkList = tbParkspaceMapper.listInParks(power.getParkList());
		}

		List dataList = new ArrayList();
		for (TbParkspace park : parkList) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("parkId", park.getId());
			map.put("parkName", park.getName());
			dataList.add(map);
		}
		ParkDataResult parkDataResult = ParkDataResult.createListDate();
		parkDataResult.putDataOnList(dataList);
		return parkDataResult;
	}

	@Override
	public ParkDataResult listTree() throws BaseException {
		
		List<TreeParkInfo>  parkTree=tbProjectMapper.treeParkList();
		ParkDataResult parkDataResult = ParkDataResult.createListDate();
		parkDataResult.putDataOnList(parkTree);
		return parkDataResult;
	}

//    @Override
//    public void parkRuleSync() throws BaseException {
//        List<TbParkspace> parkSpaceList = tbParkspaceMapper.listAll();
//        if (ListUtil.isEmpty(parkSpaceList)) {
//            _log.info("车场列表为空，同步任务已完成");
//            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
//                    ExceptionMessage.createExceptionMessage(
//                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "车场列表为空", "车场列表为空"));
//        }
//        String simpleText = "";
//        String detailText = "";
//        for (TbParkspace park : parkSpaceList) {
//            int parkId = park.getId();
//            try {
//                parkRuleSync(parkId);
//            } catch (BaseException e) {
//                simpleText += e.getExceptionMessage().getSimpleText() + "{" + parkId + "}/";
//                detailText += e.getExceptionMessage().getDetailText() + "{" + parkId + "}/";
//            } catch (Exception e) {
//                simpleText += "未知异常{" + parkId + "}/";
//                detailText += "未知异常{" + parkId + "}/";
//            }
//        }
//
//        if (!StringUtils.isBlank(detailText)) {
//            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOT_ALL_SUCCESS.getId(), null,
//                    ExceptionMessage.createExceptionMessage(
//                            ServiceCoreException.TypeEnum.EXCEPTION_NOT_ALL_SUCCESS.getDesc(), simpleText, detailText));
//        }
//        
//    }

//    @Override
//    public void parkRuleSync(int parkId) throws BaseException {
//        TbParkspace park=parkCacheInter.queryParkSpace(parkId);
//
//        if (park == null) {
//            _log.info("车场列表为空，同步任务已完成");
//            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
//                    ExceptionMessage.createExceptionMessage(
//                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "无此车场", " 车牌=" + parkId));
//        }
//
//        // 车场编号
//        String parkCode = park.getParkCode();
//        // 车场软件供应商编号
//        int supplierId = park.getSupplierId();
//
//        AdapterProxy adapterProxy = adapterParkProxyFactory.createAdapterParkProxyBySupplierId(supplierId);
//
//        List<ApParkTypeInfo> apParkTypeList = adapterProxy.getRuleAdapter().AccountRuleByParkId(parkCode);
//
//        List<TbParkingrule> tbParkRulelist = new ArrayList<TbParkingrule>();
//
//        if (ListUtil.isEmpty(apParkTypeList)) {
//            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getId(), null,
//                    ExceptionMessage.createExceptionMessage(
//                            ServiceCoreException.TypeEnum.EXCEPTION_NO_DATA_FIND.getDesc(), "此车场没有规则数据", " 车牌=" + parkId));
//        }
//
//        for (ApParkTypeInfo aprule : apParkTypeList) {
//            // 规则编码 与busyName对应
//            String busyID = aprule.getBusyID();
//            // 时段类型名称 (0分时段 1高峰时段 2非高峰时段 3非工作日)
//            String busyName = aprule.getBusyName();
//            // 表示车辆类型 (0摩托车1小型车2大型车3超大型车) 公共部分
//            int carTypeCode = aprule.getCarTypeCode();
//            // 时段结束时间00:00
//            String duringEnd = aprule.getDuringEnd();
//            // 时段内费用上限(单位分)
//            int duringHighestFee = aprule.getDuringHighestFee();
//            // 时段开始时间 00:00
//            String duringStart = aprule.getDuringStart();
//            // 24小时费用上限(单位分) 公共部分
//            int highestFeeOneDay = aprule.getHighestFeeOneDay();
//            // 在场时间或首x分钟
//            String inParkTime = aprule.getInParkTime();
//            // 首x分钟的费用(单位分)
//            int inParkTimeCost = aprule.getInParkTimeCost();
//            // 项目编码
//            String parkIdStr = aprule.getParkId();
//            // 规则编码
//            int parkTypeID = aprule.getParkTypeID();
//            // 规则名称
//            String parkTypeName = aprule.getParkTypeName();
//            // 单位时间的费用(单位元)
//            int perCost = aprule.getPerCost();
//            // 单位时间(分钟) 公共部分
//            int perTime = aprule.getPerTime();
//
//            TbParkingrule tbParkingrule = new TbParkingrule();
//            tbParkingrule.setId(tbParkingruleMapper.nextSeq());
//            tbParkingrule.setBusyName(StringUtils.isBlank(busyID) ? -1 : Integer.valueOf(busyID));
//            tbParkingrule.setCarTypeCode(carTypeCode);
//            tbParkingrule.setCreate_date(new Date());
//            tbParkingrule.setDuringEnd(duringEnd);
//            tbParkingrule.setDuringHighestFee(duringHighestFee);
//            tbParkingrule.setDuringStart(duringStart);
//            tbParkingrule.setHighestFeeOneDay(highestFeeOneDay);
//            tbParkingrule.setInParkTime(StringUtils.isBlank(inParkTime) ? -1 : Integer.valueOf(inParkTime));
//            tbParkingrule.setInParkTimeCost(inParkTimeCost);
//            tbParkingrule.setName(parkTypeName);
//            tbParkingrule.setParkID(park.getId());
//            tbParkingrule.setPerCost(perCost);
//            tbParkingrule.setPerTime(perTime);
//            tbParkingrule.setStatus(RecordStatusEnum.EFFICIENCY.getStatus());
//            tbParkingrule.setUpdate_date(new Date());
//
//            tbParkRulelist.add(tbParkingrule);
//        }
//
//        // 保存车场规则列表
//        parkBiz.syncSave(tbParkRulelist, park);
//        
//    }

}
